package com.cropdoctor.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.cropdoctor.common.CustomException;
import com.cropdoctor.common.Result;
import com.cropdoctor.mapper.VideoMapper;
import com.cropdoctor.model.properties.AliOssProperties;
import com.cropdoctor.service.impl.CourseServiceImpl;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "视频上传相关接口")
@RequestMapping("/video")
@Slf4j
public class VideoController {
    @Autowired
    CourseServiceImpl courseService;

    @Autowired
    AliOssProperties aliOssProperties;

    @Autowired
    OSS client;

    @GetMapping("/getSign")
    @ResponseBody
    protected Result<Map<String,Object>> getSignature(String dir){
        String endpoint =  aliOssProperties.getEndpoint();
        String accessId =  aliOssProperties.getAccessKeyId();
        String accessKey = aliOssProperties.getAccessKeySecret();
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);//根据参数dir计算的policy，如果和前端uploadfile中参数key的相应字段不一致的话是会报错的
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes();
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("accessId",accessId);
            map.put("policy", encodedPolicy);
            map.put("signature", postSignature);
            return  Result.success(map);
        } catch (Exception e) {
            throw new CustomException("文件上传失败!");
        }
    }
}
